/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.demo.jackson.treemodel;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;

public class JacksonTreeModelDemo {

    public static ObjectMapper getMapper() {
        return new ObjectMapper().configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
                .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    }

    public static void unmarshal(String json) throws IOException {
        // or getMapper().readValue(json, JsonNode.class);
        JsonNode rootNode = getMapper().readTree(json);
        JsonNode nameNode = rootNode.path("parent");
        //修改节点值
        if (nameNode instanceof ObjectNode) {
            ((ObjectNode) nameNode).put("name", "zhaowu");
        }
        getMapper().writeValue(System.out, rootNode);
    }

    public static void marshal() throws IOException {
        ObjectNode objectNode = getMapper().createObjectNode();
        objectNode.put("img", new byte[]{1, 1, 1, 1});
//        objectNode.putPOJO()
        getMapper().writeValue(System.out, objectNode);
    }

    public static void main(String[] args) throws IOException {
        User u = new User();
        u.setName("zz");
        u.setAge(11);
//        unmarshal("{name: 'zhangsan', age: 22, parent: { name: 'lisi', age: 88}}");
        marshal();
    }

    public static class User {
        private String name;
        private int age;
        private User parent;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public User getParent() {
            return parent;
        }

        public void setParent(User parent) {
            this.parent = parent;
        }
    }
}
